<?php
namespace App\Models;

class MemberCommission extends BaseModel
{
    protected $table = 'member_commission';

    // 获取佣金明细列表
    public function getCommissionList($where)
    {
        $rows = $this->leftJoin("member",'member_commission.mid','=','member.id')
            ->multiWhere($where)
            ->select('member_commission.*','member.nickname')
            ->orderBy("member_commission.total_money",'desc')->paginate();
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), 5);
        }

        return $rows;
    }

    /**
     * 计算提成处理
     * @param $mid int 订单购买者ID
     * @param $shopId int 店铺ID
     * @param $numArray array 订单信息
     * @param $desc string 日志描述
     * @return bool
     * @throws \Exception
     */
    public function commissionHandle($mid, $shopId, $numArray, $desc = '')
    {
        $memberModel = new Member();
        $memberInfo = $memberModel->_getOneById($mid); // 订单购买者信息
        if(!$memberInfo) {
            return false;
        }
        if($memberInfo['refer_mid'] == 0) {
            return true;
        }
        $referMid = $memberInfo['refer_mid'];
        $info = $this->_getOne(['mid' => $referMid, 'shop_id' => $shopId]); // 订单购买者提成信息
        $shop = (new Shop())->_redisGetOneBySid($shopId);
        $referMember = $memberModel->_getOneById($referMid);// 订单购买者上级信息
        $ratio = $referMember['refer_ratio'] != 0 ? $referMember['refer_ratio'] : $shop['refer_ratio']; // 每桶提成金额
        $money = bcmul($numArray['buy_num'], $ratio,2); // 计算提成金额 = 桶数 * 每桶提成金额

        $totalMoney = bcadd($info['total_money'], $money, 2);//总佣金额
        $ableMoney = bcadd($info['able_money'], $money, 2);//可提现金额
        $totalBuy = bcadd($info['total_buy'], $numArray['buy_num']);//购买数量
        $totalGift = bcadd($info['total_gift'], $numArray['gift_num']);// 总赠送数量
        $totalAmount = bcadd($info['total_amount'], $numArray['total_amount'],2);// 订单总金额

        $data = [
            'total_buy' => $totalBuy,
            'total_gift' => $totalGift,
            'total_money' => $totalMoney,
            'able_money' => $ableMoney,
            'total_amount' => $totalAmount
        ];
        try{
            // 更新用户提成信息
            $this->_update(['id' => $info['id']], $data);

            // 生成佣金明细日志
            $logData = [
                'mid' => $referMid,
                'shop_id' => $shopId,
                'admin_id' => $info['admin_id'],
                'money' => $money,
                'desc' => $desc,
                'type' => 1,
            ];
            (new MemberCommissionLog())->_save($logData);
            return true;
        }catch (\Exception $e) {
            return false;
        }
    }

    // 零售订水数量计算
    public function orderNumHandle($orderId, $mid)
    {
        $buy_num = 0;
        $gift_num = 0;
        $total_amount = 0;
        $orderInfo = (new Order())->_getOneById($orderId);
        if($orderInfo) {
            if($orderInfo['bill_id'] == 0) {
                // 非水票购买
                $buy_num += $orderInfo['bucket_num'];
                $total_amount += $orderInfo['order_amount'];
            }
            $result = $this->waterBillOrderOffLineNumHandle($mid);
            $buy_num += $result['buy_num'];
            $gift_num += $result['gift_num'];
            $total_amount += $result['total_amount'];
        }

        return ['buy_num' => $buy_num,'gift_num' => $gift_num,'total_amount' => $total_amount];
    }

    // 线下未支付水票订单购买数量计算
    protected function waterBillOrderOffLineNumHandle($mid)
    {
        $where = [
            'mid' => $mid,
            'pay_status' => 10,
            'type' => 1
        ];
        $model = new WaterBillOrder();
        $total_amount = $model->_sum($where,'order_amount');
        $buy_num = $model->_sum($where,'buy_num');
        $gift_num = $model->_sum($where,'gift_num');

        return ['buy_num' => $buy_num,'gift_num' => $gift_num,'total_amount' => $total_amount];
    }
}